//
//  SettingsViewController.m
//  RuiHeApp
//
//  Created by Jun on 2022/11/10.
//

#import "SettingsViewController.h"
#import "SettingOptionController.h"
#import "PasswordVerifyController.h"
#import "MaintenceSettingsCell.h"
#import "DevSettingTypeModel.h"
#import "DevSettingModel.h"
#import "DevSettingOptionModel.h"
#import "PasswordVerifyController.h"
//#import "SettingsListController.h"
#import "ChoiceDateTimeController.h"
#import "RHWindowTipManage.h"
#import "NSString+LenWid.h"
#import "RHDeviceModel.h"
#import "TextInputModel.h"
#import "TextInputBoxView.h"
//#import "ChoiceModeVC.h"
#import "WSDatePickerView.h"
//#import "EduOnlineManage.h"
//#import "UserModel.h"
#import "RHEndPointModel.h"
#import "RHTools.h"

@interface SettingsViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) UIView *lineV;

@property (nonatomic ,strong) QMUIButton *resetBtn;

@property (nonatomic ,strong) QMUILabel *tipsLab;
//模块类型数组
@property (nonatomic ,copy) NSArray *typeArray;
//模块类型model数组
@property (nonatomic ,strong) NSMutableArray *typeDataArray;
//类型
@property (nonatomic ,strong) NSMutableArray *itemsArray;

@property (nonatomic ,assign) NSInteger selectIndex;

@property (nonatomic ,assign) BOOL isRefreshInfo;

@property (nonatomic ,strong) ChoiceDateTimeController *choiceTimeController;

@property (nonatomic ,strong) DevSettingTypeModel *curTypeModel;
//EMS MATER PACK
@property (nonatomic ,strong) UIScrollView *typeScrollView;

@property (nonatomic, strong) MASConstraint *tableViewTopConstraint;

@property (nonatomic, strong) NSDictionary *deviceInfo;

//集装箱mppt有多组
@property (nonatomic ,strong) UIScrollView *groupScroll;

@property (nonatomic ,strong) UIView *groupListView;
//mppt组选择  ems模式选择
@property (nonatomic ,assign) NSInteger groupIndex;

@property (nonatomic ,strong) UIView *inverterSelView;

//集装箱ems模式
@property (nonatomic ,strong) UIView *scheduleView;

@property (nonatomic, strong) TextInputBoxView *inputView;

@property (nonatomic, strong) TextInputModel *inputModel;

//@property (nonatomic, strong) ChoiceModeVC *choiceModeVC;
@end

@implementation SettingsViewController

- (NSMutableArray *)typeDataArray{
    if (!_typeDataArray) {
        _typeDataArray = [NSMutableArray array];
    }
    return _typeDataArray;
}

- (NSMutableArray *)itemsArray{
    if (!_itemsArray) {
        _itemsArray = [NSMutableArray array];
    }
    return _itemsArray;
}

- (ChoiceDateTimeController *)choiceTimeController{
    if(!_choiceTimeController){
        _choiceTimeController = [[ChoiceDateTimeController alloc] init];
    }
    return _choiceTimeController;
}
/*{name: 'No set scheduling policy',key: 0},
 {name: 'Spontaneous self-use',key: 1},
 {name: 'peak-load shifting',key: 2},
 {name: 'Pv priority',key: 3},
 {name: 'Mains priority',key: 4},
 {name: 'Backup mode',key: 5},
 {name: 'Battery mode',key: 6},
 */
//-(ChoiceModeVC *)choiceModeVC
//{
//    if(!_choiceModeVC){
//        _choiceModeVC = [[ChoiceModeVC alloc]init];
//        _choiceModeVC.curIdx = -1;
//        _choiceModeVC.dataArray = @[@"No set scheduling policy",@"Spontaneous self-use",@"peak-load shifting",@"Pv priority",@"Mains priority",@"Backup mode",@"Battery mode"];
//    }
//    return _choiceModeVC;
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self getParamStatusData];
}

- (void)setupUI{
    kWeakSelf;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:UIColor.whiteColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[MaintenceSettingsCell class] forCellReuseIdentifier:SettingsInputTxtCell];
    [_tableView registerClass:[MaintenceSettingsCell class] forCellReuseIdentifier:SettingsSwitchCell];
    [_tableView registerClass:[MaintenceSettingsCell class] forCellReuseIdentifier:SettingsAddOrSubCell];
    [_tableView registerClass:[MaintenceSettingsCell class] forCellReuseIdentifier:SettingsMoreItemCell];
    [_tableView registerClass:[MaintenceSettingsCell class] forCellReuseIdentifier:SettingsCommandCell];
    [_tableView registerClass:[MaintenceSettingsCell class] forCellReuseIdentifier:SettingsDateCell];
    [_tableView registerClass:[MaintenceSettingsCell class] forCellReuseIdentifier:SettingsTextCell];
    
    [self.view addSubview:_tableView];
    
    
    
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.mas_offset(0);
        make.top.mas_offset(0);
    }];
    
    
    
    self.tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    
    
    [self.tableView addHeaderRefresh:^{
        weakSelf.isRefreshInfo = NO;
        [weakSelf getParamStatusData];
    }];
    
    
}

#pragma mark ------ 3.获取参数值
-(void)getParamStatusData
{
    RHEndPointModel *endpointModel = [self.endPointTypeModel.nodes firstObject];
    [QMUITips showLoadingInView:self.view];
    [BaseModel startGetWithCompletionAPIKey:H_getParamStatusData argument:@{@"deviceId":ValidNullData(self.deviceModel.deviceId),@"sn":ValidNullData(endpointModel.sn)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            self.deviceInfo = request.responseJSONObject[@"data"];
            //重新加载json文件
            self.deviceModel.dataInfo = self.deviceInfo;
            self.deviceModel = self.deviceModel;
            [self readDefult:self.deviceInfo];
            [self.tableView reloadData];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        
    }];
}






- (void)setDeviceModel:(RHDeviceModel *)deviceModel{
    _deviceModel = deviceModel;
    _deviceModel.inverterType = DevInverterTypeRYY6K;
    self.typeArray = @[@(SettingType_Inverter)];
    
    
}

- (void)setTypeArray:(NSArray *)typeArray{
    _typeArray = typeArray;
    [self.typeDataArray removeAllObjects];
    NSArray *titles = @[@"Master",@"Inverter",@"PCS",@"DCDCIN",@"DCDCOUT"];
    
    NSMutableArray *array = [NSMutableArray array];
    for (NSNumber *num in _typeArray) {
        DevSettingTypeModel *model = [DevSettingTypeModel getDataArray:[num integerValue] mpptGroupIndex:self.groupIndex deviceModel:self.deviceModel];
        if (model) {
            [self.typeDataArray addObject:model];
            [array addObject:[titles objectAtIndex:[num integerValue]]];
        }
    }
    
    [self.itemsArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        QMUIButton *btn = obj;
        if (idx<array.count) {
            NSString *title = array[idx];
            [btn setTitle:title forState:UIControlStateNormal];
            CGSize size = [NSString getStringSizeWith:title withStringFont:16 withWidthOrHeight:20 isWidthFixed:NO];
            [btn mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(size.width+20);
            }];
        }else{
            [btn mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(0);
            }];
        }
    }];
    
    self.selectIndex = 0;
    if (self.typeDataArray.count>0) {
        self.curTypeModel = self.typeDataArray[_selectIndex];
    }
}




#pragma mark -------  指令


//一体机 纳通的最后几个清除指令,要用参数设置的格式下发
-(void)allInOneNTclearCommand:(DevSettingModel*)model
{
    
    
}

//设置Date
- (void)dateAction:(DevSettingModel *)settingModel  section:(NSInteger)index{
    
    //    [[EOWindowTipManage shareWindowTipManage] showWithController:self.choiceTimeController];
    //    [self.choiceTimeController showAnimation];
    
    
    kWeakSelf;
    //    self.choiceTimeController.resultCallBack = ^(NSDate * _Nonnull date) {
    //        NSString *currentDate = [date stringWithFormat: dateFormatStr];
    //        settingModel.content = currentDate;
    //        [weakSelf.tableView reloadData];
    //    };
    
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDayHourMinuteSecond CompleteBlock:^(NSDate *selectDate) {
        NSString *dateFormatStr = @"yyyy/MM/dd HH:mm:ss";
        NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];
        settingModel.content = currentDate;
        [weakSelf.tableView reloadData];
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    [datePickerV show];
}



- (void)setCurTypeModel:(DevSettingTypeModel *)curTypeModel{
    _curTypeModel = curTypeModel;
    [self.tableView reloadData];
}

#pragma mark ----- 点击了设置 (参数设置)
- (void)setParamsAction:(DevSettingModel *)model{
    
    
    //判断日月元工作模式有无选择
    __block BOOL hasNullValue = NO;
    [model.properList enumerateObjectsUsingBlock:^(DevSettingModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if([obj.field isEqualToString:@"Inv1_WorkModeSet"]&&obj.content.length == 0){
            [QMUITips showError:@"please select work mode"];
            hasNullValue = YES;
            return;
        }
    }];
    
    if(hasNullValue) return;
    
    
    //密码校验
    if (Password_Check) {
        PasswordVerifyController *vc = [[PasswordVerifyController alloc] init];
        [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
        
        kWeakSelf;
        vc.callBackBlock = ^(NSString * _Nonnull password) {
                    NSDictionary *dic = [RHTools getAccountInfo];
                    if ([SafeStr(dic[@"password"]) isEqualToString:password]) {
                        [weakSelf devParamsSetFromNetwork:model];
                    }else{
                        [QMUITips showInfo:@"密码错误".rh_localized];
                    }
        };
    }else{
        [self devParamsSetFromNetwork:model];
    }

    
    
}





#pragma mark ------- 指令设置 --------
- (void)devSendCommand:(NSString *)command settingModel:(DevSettingModel *)model{
    //    NSString *url = [NSString stringWithFormat:@"%@/%@/commands/%@?devtype=%@&cmdtype=confirmed", H_devSetting,_deviceModel.devid,command,_deviceModel.devtype];
    //
    //    [SVProgressHUD show];
    //
    //    NSDictionary *para = @{model.field:@(1)};
    //
    //
    //    [DevSettingModel startPutWithCompletionAPIKey:url argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
    //        [SVProgressHUD dismiss];
    //        if (resultModel.success) {
    //
    //        }
    //    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
    //        if (resultModel.code == -400) {
    //            if([resultModel.message isEqualToString:@"当前用户无权限"]){
    //                [[ProgressHUDManage shareObject] showAlert:@"Current user does not have permission"];
    //            }else{
    //                [[ProgressHUDManage shareObject] showAlert:resultModel.message];
    //            }
    //        }else{
    //            [[ProgressHUDManage shareObject] showAlert:ValidStr(resultModel.message)?resultModel.message:@"request error"];
    //        }
    //    }];
}

#pragma mark ------ 参数设置
- (void)devParamsSetFromNetwork:(DevSettingModel *)model{
    
    
    
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    RHEndPointModel *endpointModel = [self.endPointTypeModel.nodes firstObject];
    NSDictionary *endPointDic = @{@"dataType":@"string",
                                  @"paramName":@"sn",
                                  @"value":ValidNullData(endpointModel.sn)};
    [paraListArr addObject:endPointDic];
    BOOL isCustomWorkModel = NO;
    DevSettingModel *model_work = [model.properList firstObject];
    if([model_work.field isEqualToString:@"Inv1_WorkModeSet"]){
        if ([model_work.content integerValue]==5) {
            isCustomWorkModel = YES;
        }
    }
    
    [model.properList enumerateObjectsUsingBlock:^(DevSettingModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ////自定义工作模式的禁用项要提交参数,其他模式的禁用参数项不提交
        if (obj.disable && (!isCustomWorkModel)) {
            return;
        }
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        DevSettingModel *setModel = obj;
        NSString *str = setModel.content;
        double content = [setModel.content doubleValue];
        if (setModel.ratio) {
            content = content/[setModel.ratio doubleValue];
        }
        str = [NSString stringWithFormat:@"%lf",content];
        NSDecimalNumber *numTemp = [NSDecimalNumber decimalNumberWithString:str];
        NSString *valueStr = [NSString stringWithFormat:@"%@",numTemp];
        
        [dic setObject:obj.format forKey:@"dataType"];
        [dic setObject:obj.field forKey:@"paramName"];
        [dic setObject:valueStr forKey:@"value"];
        [dic setObject:@(obj.regAddr) forKey:@"regAddr"];
        [dic setObject:@(obj.num) forKey:@"num"];
        [dic setObject:@(obj.offset) forKey:@"offset"];
        
        if([self.deviceModel.productTypeCode isEqualToString:@"HE_ALLINONE"]){
            //日月元
            if(self.deviceModel.inverterType  == DevInverterTypeRYY6K||
               self.deviceModel.inverterType  == DevInverterTypeRYY12K){
                if([setModel.field isEqualToString:@"Inv1_MachineModel"]){
                    if([numTemp integerValue]==78){
                        [dic setObject:@(77) forKey:@"value"];
                    }
                    if([numTemp integerValue]==152){
                        [model.properList enumerateObjectsUsingBlock:^(DevSettingModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            if([obj.field isEqualToString:@"Inv1_PVEnerSuPri"] && [obj.content integerValue] ==0){
                                [dic setObject:@(150) forKey:@"value"];
                            }
                            
                        }];
                        
                    }
                }
                //时间校准
                if([obj.type isEqualToString:@"date"]){
                    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                    formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";
                    NSDate *date = [formatter dateFromString:obj.content];
                    [self processTimeParams:paraListArr date:date];
                    
                }
                //充放电时间
                if([obj.field isEqualToString:@"Inv1_StartAcChTim"]||
                   [obj.field isEqualToString:@"Inv1_StopAcChTim"]||
                   [obj.field isEqualToString:@"Inv1_SecStartAcChT"]||
                   [obj.field isEqualToString:@"Inv1_SecStopAcChT"]||
                   [obj.field isEqualToString:@"Inv1_StaAcChLoadT"]||
                   [obj.field isEqualToString:@"Inv1_StopAcChLoadT"]){
                    [dic setValue:[NSString stringWithFormat:@"%04ld",[obj.content integerValue]] forKey:@"value"];
                    if(obj.content.length==0){
                        [dic setValue:@"" forKey:@"value"];
                    }
                }
            }
            //纳通
            if([self.deviceInfo[@"Inv1_InvDevType"] integerValue] == 100){
                //时间校准
                if([obj.type isEqualToString:@"date"]){
                    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                    formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";
                    NSDate *date = [formatter dateFromString:obj.content];
                    
                    [self processTimeParams:paraListArr date:date];
                }
                
            }
            
        }
        
        [paraListArr addObject:dic];
        
        //[dic addEntriesFromDictionary:@{setModel.field:@([numTemp integerValue])}];
        //移除日月元 json文件里两个无关的自定义参数参数
        NSMutableArray *removeArr = [NSMutableArray array];
        if(self.curTypeModel.settingType == SettingType_Inverter){
            [paraListArr enumerateObjectsUsingBlock:^(NSMutableDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj[@"paramName"] isEqualToString:@"SystemTimeAligned"]||[obj[@"paramName"] isEqualToString:@"Inv1_chgPri"]) {
                    [removeArr addObject:obj];
                }
            }];
        }
        if (removeArr.count>0) {
            [paraListArr removeObjectsInArray:removeArr];
        }
        
        
    }];
    

    if (paraListArr.count == 0) {
        return;
    }
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        @"deviceId": self.deviceModel.deviceId,
        @"deviceType": self.deviceModel.productTypeCode,
        @"endpointCode":endpointModel.endpointCode,
        @"paramCount":@(paraListArr.count-1),
        @"sn":endpointModel.sn,
        @"messageType": @(1),//下行
        @"namespace": @"ParamSetSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
    [QMUITips showLoading:@"设置中...".rh_localized inView:self.view];
    [BaseModel startWithCompletionAPIKey:H_controlDevice argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"设置成功".rh_localized];
            
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

#pragma mark ------- 设置参数成功的回读
-(void)readParamData:(DevSettingModel *)model
{
    [self.view endEditing:YES];
    RHEndPointModel *endpointModel = [self.endPointTypeModel.nodes firstObject];
    if(!endpointModel)return;
    
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    NSDictionary *endPointDic = @{@"dataType":@"string",
                                  @"paramName":@"sn",
                                  @"value":endpointModel.sn};
    [paraListArr addObject:endPointDic];
    
    [model.properList enumerateObjectsUsingBlock:^(DevSettingModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        DevSettingModel *setModel = obj;
        NSString *str = setModel.content;
        double content = [setModel.content doubleValue];
        if (setModel.ratio) {
            content = content/[setModel.ratio doubleValue];
        }
        str = [NSString stringWithFormat:@"%lf",content];
        NSDecimalNumber *numTemp = [NSDecimalNumber decimalNumberWithString:str];
        NSString *valueStr = [NSString stringWithFormat:@"%@",numTemp];
        
        [dic setObject:obj.format forKey:@"dataType"];
        [dic setObject:obj.field forKey:@"paramName"];
        [dic setObject:valueStr forKey:@"value"];
        [dic setObject:@(obj.regAddr) forKey:@"regAddr"];
        [dic setObject:@(obj.num) forKey:@"num"];
        [dic setObject:@(obj.offset) forKey:@"offset"];
        
        if([self.deviceModel.productTypeCode isEqualToString:@"HE_ALLINONE"]){
            //日月元
            if(self.deviceModel.inverterType  == DevInverterTypeRYY6K||
               self.deviceModel.inverterType  == DevInverterTypeRYY12K){
                if([setModel.field isEqualToString:@"Inv1_MachineModel"]){
                    if([numTemp integerValue]==78){
                        [dic setObject:@(77) forKey:@"value"];
                    }
                    if([numTemp integerValue]==152){
                        [model.properList enumerateObjectsUsingBlock:^(DevSettingModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            if([obj.field isEqualToString:@"Inv1_PVEnerSuPri"] && [obj.content integerValue] ==0){
                                [dic setObject:@(150) forKey:@"value"];
                            }
                            
                        }];
                        
                    }
                }
                //时间校准
                if([obj.type isEqualToString:@"date"]){
                    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                    formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";
                    NSDate *date = [formatter dateFromString:obj.content];
                    [self processTimeParams:paraListArr date:date];
                    
                }
                //充放电时间
                if([obj.field isEqualToString:@"Inv1_StartAcChTim"]||
                   [obj.field isEqualToString:@"Inv1_StopAcChTim"]||
                   [obj.field isEqualToString:@"Inv1_SecStartAcChT"]||
                   [obj.field isEqualToString:@"Inv1_SecStopAcChT"]||
                   [obj.field isEqualToString:@"Inv1_StaAcChLoadT"]||
                   [obj.field isEqualToString:@"Inv1_StopAcChLoadT"]){
                    [dic setValue:[NSString stringWithFormat:@"%04ld",[obj.content integerValue]] forKey:@"value"];
                    if(obj.content.length==0){
                        [dic setValue:@"" forKey:@"value"];
                    }
                }
            }
            //纳通
            if([self.deviceInfo[@"Inv1_InvDevType"] integerValue] == 100){
                //时间校准
                if([obj.type isEqualToString:@"date"]){
                    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                    formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";
                    NSDate *date = [formatter dateFromString:obj.content];
                    
                    [self processTimeParams:paraListArr date:date];
                }
                
            }
            
        }
        
        [paraListArr addObject:dic];
        
        //[dic addEntriesFromDictionary:@{setModel.field:@([numTemp integerValue])}];
        //移除日月元 json文件里两个无关的自定义参数参数
        NSMutableArray *removeArr = [NSMutableArray array];
        if(self.curTypeModel.settingType == SettingType_Inverter){
            [paraListArr enumerateObjectsUsingBlock:^(NSMutableDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj[@"paramName"] isEqualToString:@"SystemTimeAligned"]||[obj[@"paramName"] isEqualToString:@"Inv1_chgPri"]) {
                    [removeArr addObject:obj];
                }
            }];
        }
        if (removeArr.count>0) {
            [paraListArr removeObjectsInArray:removeArr];
        }
        

    }];
    
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        @"deviceId": self.deviceModel.deviceId,
        @"deviceType": self.deviceModel.productTypeCode,
        @"endpointCode":endpointModel.endpointCode,
        @"paramCount":@(paraListArr.count-1),
        @"sn":endpointModel.sn,
        @"messageType": @(1),//下行
        @"namespace": @"ParamReadSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
    [QMUITips showLoading:@"".rh_localized inView:self.view];
    [BaseModel startWithCompletionAPIKey:H_controlDevice argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"读取完成".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self getParamStatusData];
            });
            
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}

//处理日月元时间校准格式
-(void)processTimeParams:(NSMutableArray*)paramList date:(NSDate*)date
{
    NSArray *keys = @[@"Inv1_RTCYear",@"Inv1_RTCMonth",@"Inv1_RTCDay",@"Inv1_RTCHour",@"Inv1_RTCMinute",@"Inv1_RTCSecond"];
    NSArray *value = @[@(date.year%100),@(date.month),@(date.day),@(date.hour),@(date.minute),@(date.second)];
    [keys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *timeDic = [NSMutableDictionary dictionary];
        NSString *valueStr = [NSString stringWithFormat:@"%02ld",[value[idx] integerValue]];
        [timeDic setObject:@"string" forKey:@"dataType"];
        [timeDic setObject:keys[idx] forKey:@"paramName"];
        [timeDic setObject:valueStr forKey:@"value"];
        [timeDic setObject:@(1025+idx) forKey:@"regAddr"];//1025-
        [timeDic setObject:@(16) forKey:@"num"];
        [timeDic setObject:@(0) forKey:@"offset"];
        [paramList addObject:timeDic];
    }];
   
}







//读取默认值
- (void)readDefult:(NSDictionary *)dic{
    [self.typeDataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        DevSettingTypeModel *model = obj;
        
        [model readDefult:dic];
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.curTypeModel) {
        return _curTypeModel.dataList.count;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    DevSettingModel * settingModel = _curTypeModel.dataList[section];
    return settingModel.properList.count?settingModel.properList.count:1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return  UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    DevSettingModel * settingModel = _curTypeModel.dataList[section];
    UIView *headV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 30)];
    [headV setBackgroundColor:UIColor.clearColor];
    QMUILabel *lab = [[QMUILabel alloc] init];
    [lab setTextAlignment:NSTextAlignmentLeft];
    [lab setFont:[UIFont boldSystemFontOfSize:14]];
    [lab setTextColor:UIColor.blackColor];
    [lab setText:settingModel.nickname.rh_localized];
    [headV addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(30);
        make.right.mas_offset(-30);
        make.height.mas_equalTo(30);
        make.centerY.mas_offset(0);
    }];
    
    return headV;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 40.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    DevSettingModel * settingModel = _curTypeModel.dataList[section];
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 40)];
    [footView setBackgroundColor:UIColor.clearColor];
    
    QMUIButton *setBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [setBtn setBackgroundColor:CMainColorGreen];
    [setBtn setTitleColor:FontColor(@"#ffffff") forState:UIControlStateNormal];
    [setBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [setBtn.layer setCornerRadius:15];
    [setBtn setTitle:@"设置".rh_localized forState:UIControlStateNormal];
    [setBtn setEnabled:settingModel.unchange?NO:YES];
    [setBtn setHidden:settingModel.hidden];
    [footView addSubview:setBtn];
    [setBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(footView).offset(-footView.width*0.25);
        make.centerY.mas_offset(0);
        make.height.offset(kScaleW(30));
        make.width.offset(kScaleW(70));
    }];
    
    kWeakSelf;
    [[setBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf.view endEditing:YES];
        [weakSelf setParamsAction:settingModel];
    }];
    
    QMUIButton *readBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [readBtn setBackgroundColor:CMainColorGreen];
    [readBtn setTitleColor:FontColor(@"#ffffff") forState:UIControlStateNormal];
    [readBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [readBtn.layer setCornerRadius:15];
    [readBtn setTitle:@"读取".rh_localized forState:UIControlStateNormal];
    [readBtn setEnabled:settingModel.unchange?NO:YES];
    [readBtn setHidden:settingModel.hidden];
    [footView addSubview:readBtn];
    [readBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(footView).offset(footView.width*0.25);
        make.centerY.mas_offset(0);
        make.height.offset(kScaleW(30));
        make.width.offset(kScaleW(70));
    }];
    

    [[readBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf.view endEditing:YES];
        [weakSelf readParamData:settingModel];
    }];
    
    //纳通的最后一组指令,隐藏掉set
    if([self.deviceModel.deviceTypeCode isEqualToString:@"HE_ALLINONE"]&&self.curTypeModel.settingType == SettingType_Inverter){
        if(self.deviceModel.inverterType  == DevInverterTypeNT && [settingModel.nickname isEqualToString:@"Command"]){
            setBtn.hidden = YES;
            readBtn.hidden = YES;
        }
    }
    
    
    return footView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DevSettingModel * settingModel = _curTypeModel.dataList[indexPath.section];
    DevSettingModel *model = settingModel.properList.count?settingModel.properList[indexPath.row]:settingModel;
    //Switch显示开关按钮，number的时候输入数字，select的时候下拉选择list
    MaintenceSettingsCell *cell;
    if ([model.type isEqualToString:@"switch"]) {
        cell = [tableView dequeueReusableCellWithIdentifier:SettingsSwitchCell];
        cell.switchBlock = ^{
            
        };
    }else if ([model.type isEqualToString:@"number"]){
        cell = [tableView dequeueReusableCellWithIdentifier:SettingsAddOrSubCell];
    }else if ([model.type isEqualToString:@"select"]){
        cell = [tableView dequeueReusableCellWithIdentifier:SettingsInputTxtCell];
    }else if ([model.type isEqualToString:@"item"]){
        cell = [tableView dequeueReusableCellWithIdentifier:SettingsMoreItemCell];
    }else if ([model.type isEqualToString:@"command"]){
        cell = [tableView dequeueReusableCellWithIdentifier:SettingsCommandCell];
        kWeakSelf;
        cell.commandBlock = ^(DevSettingModel * _Nonnull settingModel) {
//            [weakSelf commandAction:settingModel section:indexPath.section];
        };
    }else if ([model.type isEqualToString:@"date"]){
        kWeakSelf;
        cell = [tableView dequeueReusableCellWithIdentifier:SettingsDateCell];
        cell.dateBlock = ^(DevSettingModel * _Nonnull settingModel) {
            [weakSelf dateAction:settingModel section:indexPath.section];
        };
    }else if ([model.type isEqualToString:@"text"]){
        cell = [tableView dequeueReusableCellWithIdentifier:SettingsTextCell];
    }
    
    if(cell==nil){
        return [UITableViewCell new];
    }
    
    [cell setSettingModel:model];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DevSettingModel * settingModel = _curTypeModel.dataList[indexPath.section];
    DevSettingModel *model = settingModel.properList.count?settingModel.properList[indexPath.row]:settingModel;
    
    //日月元 工作模式 禁用选项
    if(model.disable)return;
    
    
    
    MaintenceSettingsCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([model.type isEqualToString:@"select"]) {
        SettingOptionController *vc = [[SettingOptionController alloc] initWithData:model.inputModel.optionList];
        [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
        vc.curTextValue = [model.content integerValue];
        vc.selectBlock = ^(NSInteger index) {
            DevSettingOptionModel *select_model = model.inputModel.optionList[index];
            model.inputModel.content = select_model.text;
            model.content = [NSString stringWithFormat:@"%ld",select_model.textValue];
            
            [cell setSettingModel:model];
            //如果点击的是日月元
            if(self.deviceModel.inverterType == DevInverterTypeRYY6K||
               self.deviceModel.inverterType == DevInverterTypeRYY12K){
                //选择了 工作模式
                if([model.field isEqualToString:@"Inv1_WorkModeSet"]){
                    //切换工作模式
                    [settingModel changeRYYWorkMode:index];
                    //选择的工作模式和设备的当前工作模式一样才加载
                    NSInteger currentMode = [self.deviceInfo[@"Inv1_WorkModeSet"]integerValue]-1;
                    if(index == 4 && currentMode == index){
                        //处理逻辑 Machine Model, PV Energy Usage Priority 等选项逻辑并读取默认值
                        [settingModel handleRYYWorkModeWithDevInfo:self.deviceInfo];
                        [settingModel loadRYYWorkModeDataWithDevInfo:self.deviceInfo];
                    }
                    
                    //Low Cost AC Charge Mode的充放电时间要加载
                    if(index == 2 && (currentMode == index)){
                        [settingModel loadCumtomDataWithDevInfo:self.deviceInfo];
                    }
                    
                    
                    [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
                }
                //选择了 设备型号(Machine Model) 目前只有在 Self Defined Mode  工作模式下才能修改
                if([model.field isEqualToString:@"Inv1_MachineModel"]){
                    [settingModel changeRYYMachineModel:index];
                    //加载部分值
                    [settingModel loadCumtomDataWithDevInfo:self.deviceInfo];
                    [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
                }
                //选择了 光伏能量使用优先级
                if([model.field isEqualToString:@"Inv1_PVEnerSuPri"]){
                    [settingModel changeRYYPvPriority:index];
                    [settingModel loadCumtomDataWithDevInfo:self.deviceInfo];
                    [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
                }
                
                //选择了 充电优先级
                if([model.field isEqualToString:@"Inv1_chgPri"]){
                    [settingModel changeRYYChargePriority:index];
                    [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
                }
            }
        };
    }
    
    //    if([model.type isEqualToString:@"item"]){
    //        SettingsListController *vc = [[SettingsListController alloc] initWithModel:model];
    //        [self.navigationController pushViewController:vc animated:YES];
    //    }
}

#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}



-(void)dealloc
{
    
}
@end
